﻿using Ding.Helpers;
using Ding.Localization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using IMiddleware = Ding.AspNetCore.IMiddleware;

namespace Ding.Webs.Middlewares
{
    /// <summary>
    /// 语言中间件
    /// </summary>
    /// <remarks>此中间件仅为将各语言包拆开来单独使用时调用</remarks>
    public class LanguageMiddleware : IMiddleware
    {
        /// <summary>
        /// 下一个中间件
        /// </summary>
        private readonly RequestDelegate _next;

        /// <summary>
        /// 实例化
        /// </summary>
        /// <param name="next"></param>
        public LanguageMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 执行中间件拦截逻辑
        /// </summary>
        /// <param name="context">Http上下文</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var Cookies = context.RequestServices?.GetService<SmartCookies>();
            var LangOptions = Ioc.Create<IOptions<LangOptions>>();
            if (Cookies.ContainsKey("ASPNET_LANG"))
            {
                var lang = Cookies["ASPNET_LANG"];
                if (lang != LangOptions.Value.CurrentLanguage)
                {
                    Cookies.Add("ASPNET_LANG", LangOptions.Value.CurrentLanguage);
                }
            }
            else
            {
                Cookies.Add("ASPNET_LANG", LangOptions.Value.CurrentLanguage);
            }

            await _next.Invoke(context);
        }
    }
}
